use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;

use async_std::sync::Mutex;
use futures::StreamExt;
use indicatif::ProgressBar;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, QueryBuilder};
use tracing::error;

use crate::models::bili::album::BiliAlbumModel;
use crate::models::media::PictureModel;

/// [{"item_id":0,"jump_url":"","mid":0,"orientation":2,"poi":"","schema_url":"","source_type":0,"text":"琪露诺","tid":409,"type":3,"url":"","x":63888,"y":62197}
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
struct BiliPictureTag {
    item_id: i64,
    jump_url: String,
    mid: i64,
    orientation: i64,
    poi: String,
    schema_url: String,
    source_type: i64,
    text: String,
    tid: i64,
    #[serde(rename(serialize = "type", deserialize = "type"))]
    tag_type: i64,
    url: String,
    x: i64,
    y: i64,
}

/// {"img_height":2026,"img_size":4993.802734375,"img_src":"https://i0.hdslb.com/bfs/new_dyn/4e8252d22bf68b137edd3eff0855d6f2394517638.jpg","img_tags":null,"img_width":2865}
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
struct BiliPictureEntity {
    img_height: i64,
    img_size: f64,
    img_src: String,
    img_tags: Option<Vec<BiliPictureTag>>,
    img_width: i64,
}

impl FromStr for BiliPictureEntity {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> { serde_json::from_str::<BiliPictureEntity>(s) }
}

// pub async fn collect_bili_album_picture() {
//     println!("start collect");
//     let db = Arc::clone(&DATA_DB);
//     let mut qb = QueryBuilder::new("select * from bili_album;");
//
//     let lock = db.lock().await;
//     let count = BiliAlbumModel::count(lock.deref()).await;
//     let pb = ProgressBar::new(count as u64);
//     let query = qb.build().fetch(lock.deref());
//     let cache: Arc<Mutex<Vec<PictureModel>>> = Arc::new(Mutex::new(Vec::new()));
//
//     let _ = query.for_each_concurrent(16, |x| async {
//         if x.is_err() { return; }
//         let row = x.unwrap();
//         let album = match BiliAlbumModel::try_from(row) {
//             Ok(al) => al,
//             Err(err) => {
//                 error!("{}", err);
//                 return;
//             }
//         };
//
//         let pics = match serde_json::from_str::<Vec<BiliPictureEntity>>(&album.pictures) {
//             Ok(arr) => {
//                 arr.into_iter()
//                     .map(|x| {
//                         let src = x.img_src.clone();
//                         let mut path_arr = src.split('/').collect::<Vec<&str>>();
//                         let name = path_arr.pop().unwrap();
//
//                         // let tags = match serde_json::from_str::<Vec<BiliPictureTag>>(x.img_tags) {
//                         //     Ok(arr) => Some(arr),
//                         //     Err(err) => {
//                         //         error!("{}", err);
//                         //         None
//                         //     }
//                         // };
//
//                         PictureModel {
//                             name: name.to_string(),
//                             src: x.img_src,
//                             width: x.img_width,
//                             height: x.img_height,
//                             size: x.img_size,
//                             tags: Some(String::new()),
//                             deleted: false,
//                         }
//                     })
//             }
//             Err(err) => {
//                 error!("{}, src = {}", err, album.pictures);
//                 return;
//             }
//         };
//         let mut cache_lock = cache.lock().await;
//         cache_lock.extend(pics);
//         if cache_lock.len() >= 1000 {
//             PictureModel::insert_batch(lock.deref(), cache_lock.deref(), 1000).await.unwrap();
//             cache_lock.clear();
//         }
//         pb.inc(1);
//     }).await;
//     // pb.finish_and_clear();
// }